#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   encryption.sh
# Version:    1.0
# Date:       2013/12/05
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    03系统安全功能-06OpenSSL-05测试加解密文件操作
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/12/05
#             - encryption, decryption
# ----------------------------------------------------------------------
##! @TODO: setup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoSetup()
{
    # check user is root
    IsRoot
    EchoResult "check user is root"

    trap DoCleanup INT EXIT

    CmdCheck openssl

    TMPDIR=/tmp/openssl$$
    mkdir ${TMPDIR}
    EchoResult "mkdir ${TMPDIR}"

}

##! @TODO: openssl version
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoTest()
{
    # genrsa
    openssl genrsa -out ${TMPDIR}/test.key 1024
    EchoResult "openssl genrsa"

    # check test.key
    test -f ${TMPDIR}/test.key
    EchoResult "check ${TMPDIR}/test.key"


    # encryption, decryption
    # encryption
    openssl enc -e -rc4 -in ${TMPDIR}/test.key -out ${TMPDIR}/test.key.enc -pass pass:111111
    # check test.key.enc
    test -f ${TMPDIR}/test.key.enc
    EchoResult "check ${TMPDIR}/test.key.enc"
    
    # decryption
    openssl enc -d -rc4 -in ${TMPDIR}/test.key.enc -out ${TMPDIR}/test.key.dec -pass pass:111111
    # check test.key.dec
    test -f ${TMPDIR}/test.key.dec
    EchoResult "check ${TMPDIR}/test.key.dec"

    diff ${TMPDIR}/test.key ${TMPDIR}/test.key.dec
    EchoResult "openssl : encryption, decryption"

}


##! @TODO: cleanup 
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoCleanup()
{
    [ -e ${TMPDIR} ] && rm -rf ${TMPDIR}
}

# include lib files

if [ -z "$SFROOT" ]
then
    echo "SFROOT is null, pls check"
    exit 1
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/Check.sh
. ${SFROOT}/testcases/Security/lib/UserOps.sh

export LANG=C

DoSetup
DoTest
echo ""
